<template>
 
  <div id="app">
    <!-- 路由出口 + 表格内容 -->
    
      <!-- 添加按钮 -->
      <el-button type="primary" @click="openAddDialog">添加商品</el-button>
      
      <!-- 商品表格（新增3列：详情、总数、剩余量） -->
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column prop="id" label="商品id" width="180" />
        <el-table-column prop="name" label="商品名称" width="180" />
        <el-table-column prop="price" label="价格" width="180" />
        <el-table-column prop="pic" label="图片地址" width="200" />
        <el-table-column prop="detail" label="商品详情" width="200" />
        <el-table-column prop="total" label="商品总数" width="120" />
        <el-table-column prop="remaining" label="剩余量" width="120" />
        
        <!-- 操作列（保持不变） -->
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(scope.row)">修改</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteGoods(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加/修改商品弹窗（新增3个输入字段） -->
      <el-dialog v-model="dialogVisible" title="添加商品" width="600px">
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="formRef"
          label-width="80px" 
          style="padding: 20px;"
        >
          <el-form-item label="商品ID" prop="id">
            <el-input v-model="formData.id" placeholder="请输入商品ID" />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="formData.price" placeholder="请输入商品价格" />
          </el-form-item>
          <el-form-item label="图片地址" prop="pic">
            <el-input v-model="formData.pic" placeholder="请输入图片地址" />
          </el-form-item>
          <el-form-item label="商品详情" prop="detail">
            <el-input v-model="formData.detail" placeholder="请输入商品详情" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="商品总数" prop="total">
            <el-input v-model.number="formData.total" placeholder="请输入商品总数" />
          </el-form-item>
          <el-form-item label="剩余量" prop="remaining">
            <el-input v-model.number="formData.remaining" placeholder="请输入剩余量" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </span>
        </template>
      </el-dialog>
    </div>

</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'ContactView',
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      formData: {
        id: '',
        name: '',
        price: '',
        pic: '',
        detail: '',
        total: 0,
        remaining: 0
      },
      formRef: null,
      rules: {
        id: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        pic: [{ required: true, message: '请输入图片地址', trigger: 'blur' }],
        detail: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
        total: [{ required: true, message: '请输入商品总数', trigger: 'blur' }, { type: 'number', message: '请输入有效数字', trigger: 'blur' }],
        remaining: [{ required: true, message: '请输入剩余量', trigger: 'blur' }, { type: 'number', message: '请输入有效数字', trigger: 'blur' }]
      },
      currentId: null // 当前操作的商品ID
    }
  },
  mounted() {
    this.getGoodsList();
  },
  methods: {
    // 获取商品列表（自动映射新增字段）
    async getGoodsList() {
      try {
        const res = await axios.get('http://127.0.0.1:8080/goods');
        this.tableData = res.data.map(item => ({
          id: item.id,
          name: item.name,
          price: item.price,
          pic: item.pic,
          detail: item.detail,
          total: item.total,
          remaining: item.remaining
        }));
      } catch (err) {
        ElMessage.error('获取商品列表失败');
        console.error(err);
      }
    },
    
    // 打开添加弹窗（重置表单数据）
    openAddDialog() {
      this.currentId = null;
      this.formData = {
        id: '',
        name: '',
        price: '',
        pic: '',
        detail: '',
        total: 0,
        remaining: 0
      };
      this.$refs.formRef?.resetFields();
      this.dialogVisible = true;
    },
    
    // 打开编辑弹窗（复制完整商品数据）
    openEditDialog(row) {
      this.currentId = row.id;
      this.formData = { ...row }; // 包含新增字段
      this.dialogVisible = true;
    },
    
    // 提交表单（添加/修改，自动传递新增字段）
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        
        try {
          if (this.currentId) {
            // 修改商品
            await axios.put(`http://127.0.0.1:8080/goods/${this.currentId}`, this.formData);
            ElMessage.success('修改商品成功');
          } else {
            // 添加商品
            await axios.post('http://127.0.0.1:8080/goods', this.formData);
            ElMessage.success('添加商品成功');
          }
          
          this.dialogVisible = false;
          this.getGoodsList();
        } catch (err) {
          ElMessage.error(this.currentId ? '修改失败' : '添加失败');
          console.error(err);
        }
      });
    },
    
    // 删除商品（保持不变）
    async deleteGoods(id) {
      try {
        await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await axios.delete(`http://127.0.0.1:8080/goods/${id}`);
        ElMessage.success('删除成功');
        this.getGoodsList();
      } catch (err) {
        if (err.name !== 'cancel') {
          ElMessage.error('删除失败');
          console.error(err);
        }
      }
    }
  }
}
</script>

<style scoped>
.content {
  padding-top: 60px;
}


/* 操作按钮间距（保持不变） */
.el-table .el-button {
  margin-right: 5px;
}
</style>